package repositories

import (
	"errors"
	"fox/db"
	"fox/models"
	request2 "fox/request"
	response2 "fox/response"
	"gorm.io/gorm"
	"math"
)

type UserRoleRepository struct {
}

func NewUserRoleRepository() (userRoleRepository *UserRoleRepository) {
	return &UserRoleRepository{}
}

func (repository *UserRoleRepository) InsertUserRole(userRole *models.UserRole) (id int64, err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Create(userRole)
	if result.RowsAffected == 1 {
		return userRole.ID, err
	}
	return 0, result.Error
}

func (repository *UserRoleRepository) DeleteUserRoleById(id int64) (err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Delete(&models.UserRole{ID: id})
	if result.RowsAffected == 1 && result.Error == nil {
		return err
	}
	return result.Error
}

func (repository *UserRoleRepository) UpdateUserRoleById(userRole *models.UserRole) (newUserRole *models.UserRole, err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Model(&models.UserRole{ID: userRole.ID}).UpdateColumns(userRole)
	result.Scan(&newUserRole)
	return newUserRole, result.Error

}

func (repository *UserRoleRepository) SelectUserRoleById(id int64) (userRole *models.UserRole, err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Where("id = ?", id).First(&userRole)
	if result.RowsAffected == 1 {
		return userRole, nil
	}
	if result.RowsAffected == 0 {
		return nil, errors.New("没有查找到记录")
	}
	return userRole, result.Error
}

func (repository *UserRoleRepository) SelectUserRoles(userRole *request2.UserRole) (result *response2.Result, err error) {
	var (
		offset        int
		userRoles     *[]models.UserRole
		countUserRole *models.UserRole
		count         int64
		totalPage     int
	)
	countUserRole = new(models.UserRole)
	count = repository.CountUserRoles(countUserRole)
	if count == 0 {
		result.Total = 0
		result.Size = userRole.Size
		result.Page = userRole.Page
		result.Lists = make([]interface{}, 0)
		return result, err
	}

	totalPage = int(math.Ceil(float64(count) / float64(userRole.Size)))
	offset = (userRole.Page - 1) * userRole.Size
	db.GDatabase.Db.Scopes(request2.Paginate(offset, userRole.Size)).Model(&models.UserRole{}).Order(userRole.SortField + " " + userRole.Sort).Find(&userRoles)
	return &response2.Result{
		Total:     count,
		TotalPage: totalPage,
		Page:      userRole.Page,
		Size:      userRole.Size,
		Lists:     userRoles,
	}, err
}

func (repository *UserRoleRepository) CountUserRoles(userRole *models.UserRole) (count int64) {

	db.GDatabase.Db.Model(&models.UserRole{}).Count(&count)
	return count
}
